const mongoose = require('mongoose');
require('dotenv').config();

class Database {
    constructor() {
        this.uri = process.env.MONGODB_URI;
        this.options = {
            retryWrites: true,
            retryReads: true,
            writeConcern: {
                w: 'majority',
                j: true,
                wtimeout: 5000
            }
        };

        this._connect();
        this._registerEvents();
    }

    _connect() {
        mongoose.connect(this.uri, this.options)
            .then(() => {
                console.log('MongoDB连接成功');
            })
            .catch(err => {
                console.error('MongoDB连接失败:', err);
                // 连接失败时重试
                setTimeout(() => this._connect(), 5000);
            });
    }

    _registerEvents() {
        mongoose.connection.on('connected', () => {
            console.log('Mongoose已连接到数据库');
        });

        mongoose.connection.on('error', (err) => {
            console.error('Mongoose连接错误:', err);
        });

        mongoose.connection.on('disconnected', () => {
            console.log('Mongoose已断开连接，5秒后尝试重连...');
            setTimeout(() => this._connect(), 5000);
        });

        process.on('SIGINT', this._gracefulExit.bind(this));
        process.on('SIGTERM', this._gracefulExit.bind(this));
    }

    _gracefulExit() {
        mongoose.connection.close()
            .then(() => {
                console.log('Mongoose连接因应用终止而断开');
                process.exit(0);
            })
            .catch(err => {
                console.error('关闭MongoDB连接时出错:', err);
                process.exit(1);
            });
    }
}

// 导出单例实例
module.exports = new Database();